using System;
using System.Web.UI.HtmlControls;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.Context;
using PHSRAG.Insight21.Policy;
using PHSRAG.Utility;

namespace PHSRAG.Insight21.Common.DownloadBarHelper
{

    #region ExcelHost Public Class

    /// <summary>
    /// Host page for Excel reports.
    /// </summary>
    public partial class ExcelHost : BasePage
    {
        #region Instance Variables (Private)

        private ICachePolicy _cachePolicy;
        private ICachePolicy _pageCachePolicy;

        #endregion

        #region Event Handlers

        /// <summary>
        /// Gets common report headers from session and sets the respective labels with appropriate values. 
        /// Loads the UserControl for the report and remove header and UserControl fine path information from session.
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        protected void OnPageLoad(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    Response.ContentType = "application/x-msexcel";
                    Response.AddHeader("Content-Disposition", "attachment; filename=ExcelReport.xls");

                    UserContext userContext = (UserContext) _cachePolicy.GetCachedObject(UserContext.CacheKey);
                    fullName.Text = string.Format("{0}, {1}", userContext.LastName, userContext.FirstName);
                    dateGenerated.Text = DateTime.Now.ToShortDateString();
                    timeGenerated.Text = DateTime.Now.ToShortTimeString();

                    ExcelReportInfo excelReportInfo = (ExcelReportInfo) _pageCachePolicy.GetCachedObject(Keys.ExcelReportInfoKey);

                    // if the RecordCount property is set to -1 the report will not display a record count number at all.
                    // this is useful for reports that contain subreports or do not list records, and therefore
                    // cannot show a meaningful record count.
                    recordCount.Text = (excelReportInfo.RecordCount.ToString() == "-1") ? "" : excelReportInfo.RecordCount.ToString();
                    //the following is the fix for TrackIt 7285: don't display the "Record Count" Label for this Report:
                    if (excelReportInfo.RecordCountVisible != null)
                    {
                        if (excelReportInfo.RecordCountVisible == "false")
                        {
                            LabelCNT.Visible = false;
                        }
                    }
                    searchCriteria.Text = excelReportInfo.SearchCriteria;
                    reportName.Text = excelReportInfo.ReportName;

                    if (excelReportInfo.FundCount > 0)
                    {
                        //add a new row after the record count row to display the fundcount.
                        //This row has to be added dynamically as static hidden rows hide the corresponding rows in excel
                        for (int i = 0; i < headerInfo.Rows.Count; i++)
                        {
                            if (headerInfo.Rows[i].ID == "recordCountRow")
                            {
                                HtmlTableRow tr = new HtmlTableRow();
                                HtmlTableCell tc = new HtmlTableCell();
                                tc.InnerHtml = "<b>Fund Count:</b>";
                                tr.Cells.Add(tc);

                                tc = new HtmlTableCell();
                                tc.Align = "left";
                                tc.InnerText = excelReportInfo.FundCount.ToString();
                                tr.Cells.Add(tc);

                                headerInfo.Rows.Insert(i + 1, tr);
                                break;
                            }
                        }
                    }

                    placeHolder.Controls.Clear();
                    placeHolder.Controls.Add(LoadControl(excelReportInfo.ReportControlFilePath));
                }
                catch (Exception ex)
                {
                    annunciator.Visible = true;
                    annunciator.Title = "The following errors occurred while ExcelHost.aspx page was trying to load a report in excel:";
                    annunciator.Message = ExceptionReport.GetExceptionInfo(ex, false);
                }
            }
        }

        protected void OnUnload(object sender, EventArgs e)
        {
            placeHolder.Dispose();
            placeHolder = null;
            Dispose();
            GC.Collect(1);
            GC.WaitForPendingFinalizers();
            GC.Collect(1);
        }

        #endregion

        #region Web Form Designer generated code

        /// <summary>
        /// Wed Form Designer generated code - Initializes page
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);

            _cachePolicy = (Policy.ICachePolicy) Session[Policy.Names.CachePolicyKey];
            _pageCachePolicy = (Policy.ICachePolicy) Session[Policy.Names.CachePolicyKey];
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.OnPageLoad);
            this.Unload += new System.EventHandler(this.OnUnload);
        }

        #endregion
    }

    #endregion

    #region Excel Report Info Struct

    /// <summary>
    /// Struct to be used by the ExcelHost to load the report.
    /// </summary>

    #endregion
}